import { Config, App, Inject, Init, Provide } from "@midwayjs/decorator";
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { OrderInfoEntity } from '../entity/info';
import { DemoUserInfoEntity } from '../../demo/entity/info';
import { PluginService } from '../../../modules/plugin/service/info';
import { LoginlistInfoEntity } from '../../loginlist/entity/info';
import { LoginlistInfoBind } from '../../loginlist/entity/infoBind';
import { AnchorInfoEntity } from '../../anchor/entity/info';
import { AnchorInfoTypeEntity } from '../../anchor/entity/infoType';
import { PaySettingAlipayEntity } from "../../paySetting/entity/alipay"
import { TaskSystemTaskInfoEntity } from "../../tasksystem/entity/task_info"
import { FlockInfoEntity } from "../../flock/entity/info"
import { GoldTypeListEntity } from "../../gold_type_list/entity/list"
import { MemberUserInfoEntity } from "../../member/entity/info"


import { AlipaySdk } from 'alipay-sdk';
import * as crypto from 'crypto';
let TLSSigAPIv2 = require('tls-sig-api-v2');
import axios from 'axios';
import * as fs from 'fs';
import * as path from 'path';
import { IMidwayKoaApplication } from '@midwayjs/koa';

// import * as WxPay from 'wechatpay-node-v3'; // 支持使用require

let WxPay = require('wechatpay-node-v3');
import * as request from 'superagent';

/**
 * order模块-订单信息服务
 */
@Provide()
export class OrderPayService extends BaseService {

  @App()
  app: IMidwayKoaApplication;

  @InjectEntityModel(DemoUserInfoEntity)
  demoUserInfoEntity: Repository<DemoUserInfoEntity>;

  @InjectEntityModel(OrderInfoEntity)
  orderInfoEntity: Repository<OrderInfoEntity>;

  @InjectEntityModel(LoginlistInfoEntity)
  loginlistInfoEntity: Repository<LoginlistInfoEntity>;

  @InjectEntityModel(LoginlistInfoBind)
  loginlistInfoBind: Repository<LoginlistInfoBind>;

  @InjectEntityModel(AnchorInfoTypeEntity)
  anchorInfoTypeEntity: Repository<AnchorInfoTypeEntity>;

  @InjectEntityModel(AnchorInfoEntity)
  anchorInfoEntity: Repository<AnchorInfoEntity>;

  // 获取支付信息
  @InjectEntityModel(PaySettingAlipayEntity)
  paySettingAlipayEntity: Repository<PaySettingAlipayEntity>;

  // 通知消息
  @InjectEntityModel(TaskSystemTaskInfoEntity)
  taskSystemTaskInfoEntity: Repository<TaskSystemTaskInfoEntity>;

  // 社群
  @InjectEntityModel(FlockInfoEntity)
  flockInfoEntity: Repository<FlockInfoEntity>;

  // 金币充值
  @InjectEntityModel(GoldTypeListEntity)
  goldTypeListEntity: Repository<GoldTypeListEntity>;

  // 金币充值
  @InjectEntityModel(MemberUserInfoEntity)
  memberUserInfoEntity: Repository<MemberUserInfoEntity>;



  @Inject()
  ctx;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.orderInfoEntity);
  }

  async orderInfo(orderId: number) {
    return "订单不存在或不是可支付的状态";
  }

  @Inject()
  pluginService: PluginService;

  async goodsInfo(goodsId: number) {
    // 查找单个
    let data: any = await this.demoUserInfoEntity.findOneBy({ id: goodsId });
    let anchorPage = await this.anchorInfoEntity.findBy({ anchor: String(goodsId) });
    console.log(data, anchorPage, 'goodsId', this.orderInfoEntity.findOneBy)
    data.anchorList = anchorPage
    return data
  }

  /**
 * 支付宝App支付
 * @param goodsId
 */
  // 支付宝支付
  async aliApp(goodsId: number, orderType: number, orderPayType: any = 0, goldAmount: any = 0) {
    // 支付类型 orderPayType 0 h5 1 会员
    console.log(orderType, 'flockData')
    let unitPrice = 0
    let productName = ""
    let anchorName = ""
    let productId = 0
    let memberId = ""

    // 查找单个
    let data = await this.demoUserInfoEntity.findOneBy({ id: goodsId });
    // 生成订单号
    let date = new Date()
    let year = date.getFullYear() + ''
    let _mount = date.getMonth() + 1
    let _day = date.getDate()
    let mount = _mount < 10 ? ('0' + _mount) : _mount
    let day = _day < 10 ? ('0' + _day) : _day
    let curStartTime = year + '-' + mount + '-' + day + " 00:00:00"
    let curEndTime = year + '-' + mount + '-' + day + " 23:59:59"
    let orderTimer = year + mount + day
    let sql = "select count(*) from order_info where createTime >= '" + curStartTime + "' and createTime <= '" + curEndTime + "'"
    let res = await this.nativeQuery(sql);
    let ordernum = Number(res[0]['count(*)'])
    let endStr = ""
    if (ordernum < 10) {
      endStr = ('00' + (ordernum + 1))
    }
    if (10 <= ordernum && ordernum < 100) {
      endStr = ('0' + (ordernum + 1))
    }
    if (100 <= ordernum && ordernum < 1000) {
      endStr = (ordernum + 1) + ''
    }
    let _num = orderTimer + endStr
    console.log(year, mount, day, 'goodsId', res[0]['count(*)'], _num)

    let anchorItem: any = await this.demoUserInfoEntity.findOneBy({ id: goodsId })
    let payName = 'admin' // 支付人
    if (orderType == 0) {
      productName = data.name
      anchorName = anchorItem.nickname
      productId = goodsId
      unitPrice = anchorItem.unitPrice
      // 创建订单
      // let param = {
      //   orderNumber: _num,
      //   user: 'admin',
      //   quantity: 1,
      //   totalPrice: unitPrice,
      //   product: productName,
      //   status: 0,
      //   paymentMethod: 0,
      //   deliveryAddress: "无",
      //   orderTime: new Date(),
      //   tradeNo: "",
      //   anchorId: productId,
      //   orderType,
      //   anchorName: anchorName,
      // }
      // const createResult = await super.add(param);
    }

    // 会员
    if (orderType == 2) {
      let sql = "select * from dict_info where typeId = 23 and id = " + Number(goodsId)
      let sqlUser = "select * from member_user_info where id = " + Number(this.ctx.header.token)
      let memberItem: any = await this.nativeQuery(sql)
      let userItem: any = await this.nativeQuery(sqlUser)
      let userId = this.ctx.header.token
      let userName = userItem[0].nickname
      unitPrice = Number(memberItem[0].remark)
      productName = memberItem[0].name
      productId = userId
      anchorName = userName
      memberId = memberItem[0].value
      payName = userName
    }

    // 社群
    if (orderType == 3) {
      let flockData = await this.flockInfoEntity.findOneBy({ id: goodsId });
      productId = goodsId
      unitPrice = Number(flockData.price)
      productName = flockData.payName
    }

    // 金币充值
    if (orderType == 4) {
      let userId = this.ctx.header.token
      let sqlUser = "select * from member_user_info where id = " + Number(this.ctx.header.token)
      let userItem: any = await this.nativeQuery(sqlUser)
      payName = userItem[0].nickname
      if (goodsId) {
        let goldData: any = await this.goldTypeListEntity.findOneBy({ id: goodsId });
        productId = goodsId
        memberId = userId
        unitPrice = Number(goldData.amount)
        productName = goldData.name
      } else {
        productId = null
        memberId = userId
        unitPrice = Number(goldAmount)
        productName = '自定义金额'
      }
    }

    let memberParam = {
      orderNumber: _num,
      user: payName,
      quantity: 1,
      totalPrice: unitPrice,
      product: productName,
      status: 0,
      paymentMethod: 0,
      deliveryAddress: "无",
      orderTime: new Date(),
      tradeNo: "",
      anchorId: productId,
      memberId: memberId,
      orderType,
      anchorName: anchorName,
    }
    console.log(memberParam, 'memberParam')
    const createResult = await super.add(memberParam);

    let paySetting = await this.paySettingAlipayEntity.findOneBy({ id: 1 })
    let { aliAppId, applicationId, privateKey, alipayPublicKey, returnUrl, notifyUrl } = paySetting
    const alipaySdk = new AlipaySdk({
      appId: aliAppId,
      privateKey,
      alipayPublicKey,
      gateway: 'https://openapi.alipay.com/gateway.do',
    });

    const result = alipaySdk.pageExec('alipay.trade.wap.pay', {
      bizContent: {
        out_trade_no: _num,
        total_amount: unitPrice,
        subject: productName,
        product_code: 'QUICK_WAP_WAY',
        seller_id: applicationId,
      },
      return_url: returnUrl,
      notify_url: notifyUrl,
      redirect_uri: 'http://admin-dy.dearweb.cn/apid/apid/orderResult'
    });
    // 返回支付链接
    return result
  }

  // 支付宝支付结果
  async orderResult(query: any) {
    // 查找单个
    let { out_trade_no, trade_status } = query
    let data = await this.orderInfoEntity.findOneBy({ orderNumber: out_trade_no });
    if (trade_status == 'TRADE_SUCCESS') {
      let sql = 'update order_info set status = 1 WHERE orderNumber =' + out_trade_no
      let res = await this.nativeQuery(sql);
      let dataLogin = await this.orderInfoEntity.findOneBy({ orderNumber: out_trade_no });
      // 添加前导零的函数
      function padZero(num) {
        return num < 10 ? '0' + num : num;
      }

      // 实时更新时间的函数
      function updateTime(dateTime: any = new Date()) {
        const now = dateTime;
        let year = now.getFullYear() + ''
        let _mount = now.getMonth() + 1
        let _day = now.getDate()
        const hours = now.getHours();
        const minutes = now.getMinutes();
        const seconds = now.getSeconds();

        const formattedHours = padZero(hours);
        const formattedMinutes = padZero(minutes);
        const formattedSeconds = padZero(seconds);

        return year + '-' + _mount + '-' + _day + " " + `${formattedHours}:${formattedMinutes}:${formattedSeconds}`
      }
      // 相册
      if (dataLogin.orderType == 1) {
        function generateUniqueId() {
          // 获取当前时间戳
          const timestamp = Date.now().toString();
          // 生成一个随机数，可以根据需要调整位数
          const randomNumber = Math.floor(100000000 + Math.random() * 900000000);
          // 拼接时间戳和随机数，然后截取前10位
          return (timestamp + randomNumber.toString()).substr(0, 10);
        }
        // 使用函数生成唯一标识符
        const uniqueId = generateUniqueId();
        let params = {
          loginCode: uniqueId,
          status: 0,
          type: 0,
          generateTime: new Date(),
          useTime: null,
          remark: '',
          relatedOrder: out_trade_no,
          relatedAnchor: dataLogin.anchorId,
          username: 'admin',
          anchorName: dataLogin.anchorName,
        }
        let bindParams = {
          updateTime: new Date(),
          createTime: new Date(),
          loginCode: params.loginCode,
          type: 0,
          bindId: dataLogin.anchorId,
        }
        // 生成code
        await this.loginlistInfoEntity.save(params)
        // 生成绑定数据
        await this.loginlistInfoBind.save(bindParams)
      }
      // 会员
      if (dataLogin.orderType == 2) {
        console.log(updateTime(), 'updateTime')
        let _datime = {
          1: 30,
          2: 90,
          3: 365,
          4: 10365
        }
        let expireTime = Number(dataLogin.memberId)
        let now = new Date()
        let _date = new Date(now.getTime() + _datime[expireTime] * 24 * 3600 * 1000);
        // let sql = 'update member_user_info set level = ' + dataLogin.memberId + ', openTime = "' + updateTime() + ', expireTime = "' + updateTime(_date) + ' " WHERE id =' + dataLogin.anchorId
        // console.log(sql, 'updateTime222')
        await this.memberUserInfoEntity.update({ id: Number(dataLogin.anchorId) }, {
          level: Number(dataLogin.memberId),
          openTime: updateTime(),
          expireTime: updateTime(_date)
        })
        // let res = await this.nativeQuery(sql);
        let params = {
          "title": "开通会员",
          "content": "开通会员成功",
          "type": 0,
          "status": 1,
          "sender": "",
          "receiver": Number(dataLogin.memberId),
          "time": updateTime(),
          "orderNumber": out_trade_no,
          "priority": 0
        }
        await this.taskSystemTaskInfoEntity.save(params)
      }
      //  社群
      if (dataLogin.orderType == 3) {
        function generateUniqueId() {
          // 获取当前时间戳
          const timestamp = Date.now().toString();
          // 生成一个随机数，可以根据需要调整位数
          const randomNumber = Math.floor(100000000 + Math.random() * 900000000);
          // 拼接时间戳和随机数，然后截取前10位
          return (timestamp + randomNumber.toString()).substr(0, 10);
        }
        // 使用函数生成唯一标识符
        const uniqueId = generateUniqueId();
        let params = {
          loginCode: uniqueId,
          status: 0,
          type: 0,
          generateTime: new Date(),
          useTime: null,
          remark: '',
          relatedOrder: out_trade_no,
          relatedAnchor: dataLogin.anchorId,
          username: 'admin',
          anchorName: dataLogin.anchorName,
        }
        let bindParams = {
          updateTime: new Date(),
          createTime: new Date(),
          loginCode: params.loginCode,
          type: 0,
          bindId: dataLogin.anchorId,
        }
        // 生成code
        await this.loginlistInfoEntity.save(params)
        // 生成绑定数据
        await this.loginlistInfoBind.save(bindParams)
      }
      //  积分充值
      if (dataLogin.orderType == 4) {
        let setMealId = dataLogin.anchorId
        let userId = Number(dataLogin.memberId)
        let setMealItem: any = await this.goldTypeListEntity.findOneBy({ id: Number(setMealId) });
        let userItem: any = await this.memberUserInfoEntity.findOneBy({ id: userId });
        let goldNum = setMealItem.gold
        let isAdd = await this.taskSystemTaskInfoEntity.findOneBy({ orderNumber: out_trade_no })
        if (!isAdd) {
          this.memberUserInfoEntity.update({ id: userId }, { points: userItem.points + goldNum })
          let params = {
            "title": "积分充值",
            "content": "积分充值会员成功,金币加" + goldNum,
            "type": 0,
            "status": 1,
            "sender": "",
            "receiver": Number(dataLogin.memberId),
            "time": updateTime(),
            "orderNumber": out_trade_no,
            "priority": 0
          }
          await this.taskSystemTaskInfoEntity.save(params)
        }
      }
    }
    return 'success'
  }

  // 查询订单状态
  async getOrderState(query: any) {
    let { tradeNo } = query
    let res = await this.orderInfoEntity.findOneBy({ orderNumber: tradeNo });
    console.log(res, 'res')
    // 状态 0-图片 1-群聊 2-会员 3-社群 4-金币充值
    if (res.orderType == 0) {
      let token = await this.loginlistInfoEntity.findOneBy({ relatedOrder: tradeNo });
      return token
    }
    if (res.orderType == 2) {
      return res
    }
    // 群聊订单
    if (res.orderType == 3) {
      let detail: any = await this.flockInfoEntity.findOneBy({ id: Number(res.anchorId) })
      let resCode = {
        flockQrCode: detail.flockQrCode,
        flockQrCodeNumber: detail.flockQrCodeNumber,
        orderType: 3
      }
      return resCode
    }
    // 金币充值订单
    if (res.orderType == 4) {
      return res
    }
    // let data = await this.orderInfoEntity.findOneBy({ orderNumber: tradeNo });
    // function generateUniqueId() {
    //   // 获取当前时间戳
    //   const timestamp = Date.now().toString();
    //   // 生成一个随机数，可以根据需要调整位数
    //   const randomNumber = Math.floor(100000000 + Math.random() * 900000000);
    //   // 拼接时间戳和随机数，然后截取前10位
    //   return (timestamp + randomNumber.toString()).substr(0, 10);
    // }
    // // 使用函数生成唯一标识符
    // const uniqueId = generateUniqueId();
    // /*
    //   @Column({ comment: '登陆码', length: 50 })
    //   loginCode: string;
    //   @Column({ comment: '用户名', length: 50 })
    //   username: string;
    //   @Column({ comment: '状态 0-未使用 1-已使用', default: 0 })
    //   status: number;
    //   @Column({ comment: '类型 0-普通 1-VIP', default: 0, type: 'tinyint' })
    //   type: number;
    //   @Column({ comment: '生成时间', type: 'datetime' })
    //   generateTime: Date;
    //   @Column({ comment: '使用时间', type: 'datetime', nullable: true })
    //   useTime: Date;
    //   @Column({ comment: '备注', nullable: true })
    //   remark: string;
    //   @Column({ comment: '关联订单', nullable: true })
    //   relatedOrder: string;
    //   @Column({ comment: '关联主播', nullable: true })
    // */
    // if (!token) {
    //   let params = {
    //     loginCode: uniqueId,
    //     status: 0,
    //     type: 0,
    //     generateTime: new Date(),
    //     useTime: null,
    //     remark: '',
    //     relatedOrder: tradeNo,
    //     relatedAnchor: data.anchorId,
    //     username: 'username'
    //   }
    //   let bindParams = {
    //     updateTime: new Date(),
    //     createTime: new Date(),
    //     loginCode: params.loginCode,
    //     type: 0,
    //     bindId: data.anchorId,

    //   }
    //   // 生成code
    //   await this.loginlistInfoEntity.save(params)
    //   // 生成绑定数据
    //   await this.loginlistInfoBind.save(bindParams)
    //   return params
    // } else {
    // }
  }

  // 获取主播资源
  async getClientAnchorList(queryData) {
    let { code } = queryData
    let data = await this.loginlistInfoBind.findBy({ loginCode: code });
    if (data.length != 0) {
      let item = data[0]
      let anchordata = await this.demoUserInfoEntity.findBy({ id: Number(item.bindId), });
      return anchordata
    }
    return '未绑定主播'
  }

  // 获取主播相册
  async getClientAnchorAlbumList(queryData: any) {
    let user = await this.loginlistInfoBind.findBy({ loginCode: queryData.code })
    console.log(user, 'queryDataqueryDataqueryData', queryData.code)
    if (!queryData.code || user.length == 0) {
      throw new CoolCommException('用户不存在');
    }
    let sqlPage = "select * from anchor_info where status = 1 and anchor = " + queryData.id + " and labels = " + queryData.type + " order by createTime desc"
    console.log(sqlPage)
    let anchordata = await this.sqlRenderPage(sqlPage, queryData, false);
    // let anchordata = await this.anchorInfoEntity.findBy({ anchor: queryData.id });
    for (let item in anchordata.list) {
      let id = anchordata.list[item]['id']
      let anchorPhoto = await this.anchorInfoTypeEntity.createQueryBuilder()
        .where("anchorId = :anchorId", { anchorId: String(id) })
        .andWhere("type = :type", { type: queryData.type })
        .getMany();
      // findBy({ anchorId: String(id) },{type:1});
      console.log(item, 'item')
      anchordata.list[item]['photo'] = anchorPhoto
    }
    console.log(anchordata, 'anchordata')
    return anchordata
  }

  // 获取秘钥
  async getGenSig(query: any) {
    console.log(query, 'query')
    var api = new TLSSigAPIv2.Api(1600052836, "b1e56b26c59b23c39c2455d94f5c5222391ab9541ee36065475014d7344e9cb0");
    var sig = api.genSig(query.userId, 86400 * 180);
    console.log(sig, 'sig');
    return sig
  }

  // 微信支付 获取秘钥
  async checkSignature(query: any) {
    // signature=9cacb0e4458b200854158efecf81604ede12bae1&echostr=7563610600513320188&timestamp=1727608060&nonce=1767909883
    console.log(query, 'query')
    let token = '1pg40RZeCzT9FksIZwAtdXCa0V4yxDu6'
    let { timestamp, nonce, signature, echostr } = query
    // 1、将token、timestamp、nonce三个参数按照字典序排序
    const arr = [token, timestamp, nonce].sort();
    // 2、将三个参数字符串拼接成一个字符串进行sha1加密
    const result = crypto
      .createHash('sha1')
      .update(arr.join(''))
      .digest('hex')
    // 3、加密结果与signature比较，相同则验证通过，否则验证失败
    // return result === signature;
    console.log(result, '-----', echostr)
    console.log(signature)
    if (result === signature) {
      // 如果签名正确，原样返回echostr参数内容
      return echostr
    } else {
      // 如果签名错误，返回错误信息
      throw new Error('如果签名错误');
    }
  }

  // 获取openid
  // 根据微信code获取 openid
  async getWxOpenId(query) {
    let { code } = query
    let paySetting = await this.paySettingAlipayEntity.findOneBy({ id: 1 })
    let { appid, secret } = paySetting
    try {
      const res = await axios.get(
        'https://api.weixin.qq.com/sns/oauth2/access_token',
        {
          params: {
            appid,
            secret,
            code,
            grant_type: 'authorization_code'
          },
        }
      )
      console.log(res, 'a')
      return {
        openid: res.data.openid
      };
    } catch (error) {
      return error.response.request.data;
    }
  }

  // 微信支付订单
  async getPrepayInfo(bodyData) {
    let paySetting = await this.paySettingAlipayEntity.findOneBy({ id: 1 })
    let { appid, mchid, apiclient_key, apiclient_cert } = paySetting
    let { openid, goodsId, orderType } = bodyData
    let unitPrice: any = 0
    let productName: any = ""
    let anchorName: any = ""
    // 查找单个
    let data: any = {}
    if (bodyData.orderType != 3) {
      data = await this.demoUserInfoEntity.findOneBy({ id: goodsId });
      unitPrice = Number(data.unitPrice)
      productName = data.name
      anchorName = data.nickname
    } else {
      data = await this.flockInfoEntity.findOneBy({ id: goodsId });
      unitPrice = Number(data.price)
      productName = data.payName
      anchorName = data.payName
    }
    console.log(data, 'data')
    // 生成订单号
    let date = new Date()
    let year = date.getFullYear() + ''
    let _mount = date.getMonth() + 1
    let _day = date.getDate()
    let mount = _mount < 10 ? ('0' + _mount) : _mount
    let day = _day < 10 ? ('0' + _day) : _day
    let curStartTime = year + '-' + mount + '-' + day + " 00:00:00"
    let curEndTime = year + '-' + mount + '-' + day + " 23:59:59"
    let orderTimer = year + mount + day
    let sql = "select count(*) from order_info where createTime >= '" + curStartTime + "' and createTime <= '" + curEndTime + "'"
    let res = await this.nativeQuery(sql);
    let ordernum = Number(res[0]['count(*)'])
    let endStr = ""
    if (ordernum < 10) {
      endStr = ('00' + (ordernum + 1))
    }
    if (10 <= ordernum && ordernum < 100) {
      endStr = ('0' + (ordernum + 1))
    }
    if (100 <= ordernum && ordernum < 1000) {
      endStr = (ordernum + 1) + ''
    }
    let _num = orderTimer + endStr

    // let anchorItem: any = await this.demoUserInfoEntity.findOneBy({ id: goodsId })

    // 创建订单
    let paramSystem = {
      orderNumber: _num,
      user: 'admin',
      quantity: 1,
      totalPrice: unitPrice,
      product: productName,
      status: 0,
      paymentMethod: 1,
      deliveryAddress: "无",
      orderTime: new Date(),
      tradeNo: "",
      anchorId: goodsId,
      orderType, // 订单类型
      anchorName: anchorName
    }
    // 创建系统订单
    const createResult = await super.add(paramSystem);
    console.log(createResult, 'out_trade_no')

    const filePathkey = path.join(
      this.app.getBaseDir(),
      '..',
      'src',
      'modules',
      'order',
      'service',
      'cert',
      apiclient_key
    );
    const filePathCert = path.join(
      this.app.getBaseDir(),
      '..',
      'src',
      'modules',
      'order',
      'service',
      'cert',
      apiclient_cert
    );
    const pay = new WxPay({
      appid, // '直连商户申请的公众号或移动应用appid'
      mchid,
      publicKey: fs.readFileSync(filePathCert), // 公钥
      privateKey: fs.readFileSync(filePathkey), // 秘钥
    });

    try {
      let params = {
        appid,
        mchid,
        "out_trade_no": _num,
        "description": "平面设计VIP套餐",
        "notify_url": "https://admin-dy.dearweb.cn/apid/apid/wxOrderResult",
        "amount": {
          "total": Math.floor(Number(unitPrice) * 100),
          "currency": "CNY"
        },
        "payer": {
          openid
        }
      }
      const result1 = await pay.transactions_jsapi(params);
      console.log(result1, 'result12', unitPrice)
      result1.data.out_trade_no = _num
      return result1
    } catch (error) {
      console.log(error, 'error')
      return error
    }
  }

  // 微信回调
  async wxOrderResult(query: any) {
    let paySetting = await this.paySettingAlipayEntity.findOneBy({ id: 1 })
    let { appid, mchid, apiclient_key, apiclient_cert } = paySetting
    // 查找单个
    let key = 'd8a7u2l6i4z1f6a1t1k4n9o9n9z4g9n7' // 解密
    const filePathkey = path.join(
      this.app.getBaseDir(),
      '..',
      'src',
      'modules',
      'order',
      'service',
      'cert',
      apiclient_key
    );
    const filePathCert = path.join(
      this.app.getBaseDir(),
      '..',
      'src',
      'modules',
      'order',
      'service',
      'cert',
      apiclient_cert
    );
    const pay = new WxPay({
      appid, // '直连商户申请的公众号或移动应用appid'
      mchid,
      publicKey: fs.readFileSync(filePathCert), // 公钥
      privateKey: fs.readFileSync(filePathkey), // 秘钥
    });
    let { resource } = query
    const result = pay.decipher_gcm(resource.ciphertext, resource.associated_data, resource.nonce, key)
    console.log(result, 'result')
    let { out_trade_no, trade_state } = result
    // let data = await this.orderInfoEntity.findOneBy({ orderNumber: out_trade_no });
    console.log(trade_state == 'SUCCESS', '222')
    if (trade_state == 'SUCCESS') {
      let sql = 'update order_info set status = 1 WHERE orderNumber=' + out_trade_no
      let res = await this.nativeQuery(sql);

      let dataLogin = await this.orderInfoEntity.findOneBy({ orderNumber: out_trade_no });
      function generateUniqueId() {
        // 获取当前时间戳
        const timestamp = Date.now().toString();
        // 生成一个随机数，可以根据需要调整位数
        const randomNumber = Math.floor(100000000 + Math.random() * 900000000);
        // 拼接时间戳和随机数，然后截取前10位
        return (timestamp + randomNumber.toString()).substr(0, 10);
      }
      // 使用函数生成唯一标识符
      const uniqueId = generateUniqueId();
      let params = {
        loginCode: uniqueId,
        status: 0,
        type: 0,
        generateTime: new Date(),
        useTime: null,
        remark: '',
        relatedOrder: out_trade_no,
        relatedAnchor: dataLogin.anchorId,
        username: 'admin',
        anchorName: dataLogin.anchorName,
      }
      let bindParams = {
        updateTime: new Date(),
        createTime: new Date(),
        loginCode: params.loginCode,
        type: 0,
        bindId: dataLogin.anchorId,

      }
      // 生成code
      await this.loginlistInfoEntity.save(params)
      // 生成绑定数据
      await this.loginlistInfoBind.save(bindParams)

    }
    return {
      return_code: trade_state
    }
  }
}
